package com.mds.organ.web.screens.organ;

import com.haulmont.cuba.core.global.Messages;
import com.haulmont.cuba.gui.components.Window;
import com.haulmont.cuba.gui.model.CollectionLoader;
import com.haulmont.cuba.gui.screen.*;
import com.mds.organ.entity.Organ;
import com.mds.organ.entity.OrganType;
import org.apache.commons.lang3.StringUtils;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@UiController("mdsorgan_OrganSelect")
@UiDescriptor("organ-select.xml")
@LoadDataBeforeShow()
public class OrganSelect extends Screen {
    private List<OrganType> organTypeLst;

    private String caption;

    @Inject
    private CollectionLoader<Organ> organsDl;

    @Inject
    protected Messages messages;

    public void setOrganTypes(List<OrganType> type){
        this.organTypeLst = type;
    }

    public void setCaption(String caption){
        this.caption = caption;
    }

    @Subscribe
    public void onBeforeShow(BeforeShowEvent event) {
        initData();
    }

    private void initData(){
        if(organTypeLst == null || organTypeLst.size()==0){
            organTypeLst=new ArrayList<>();
            organTypeLst.add(OrganType.ORGAN);
            organTypeLst.add(OrganType.DEPT);
            organTypeLst.add(OrganType.DISTRICT);
            organTypeLst.add(OrganType.POSITION);
        }


        organsDl.setParameter("organType",organTypeLst);

        if(StringUtils.isEmpty(caption)){ //设置默认标题
            String defaultCap=this.getWindow().getCaption();
            StringBuilder otStr=new StringBuilder();
            for (OrganType ot: organTypeLst ) {
                if(otStr.length()>0){
                    if(!otStr.substring(otStr.length()-1).equals(",")){
                        otStr.append(",");
                    }
                }

                switch (ot){
                    case ORGAN:
                        otStr.append(messages.getMessage(OrganType.class,"OrganType.ORGAN"));
                        break;
                    case DEPT:
                        otStr.append(messages.getMessage(OrganType.class,"OrganType.DEPT"));
                        break;
                    case DISTRICT:
                        otStr.append(messages.getMessage(OrganType.class,"OrganType.DISTRICT"));
                        break;
                    case POSITION:
                        otStr.append(messages.getMessage(OrganType.class,"OrganType.POSITION"));
                        break;
                    default:
                        break;
                }
            }
            this.caption = String.format("%s ( %s )",defaultCap,otStr.toString());
        }

        this.getWindow().setCaption(this.caption);


    }
}